package com.chen.recruit.common.utils;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.chen.recruit.common.constants.SysConstants;
import com.chen.recruit.domain.dto.UserDto;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * 系统工具类
 *
 * @author cgy
 * @date 2022/09/04
 */
@Component
@RequiredArgsConstructor
public class SysUtils {

    public final RedisTemplate<String, Object> redisTemplate;

    /**
     * 对map中的value进行排序
     */
    public static <K extends Comparable, V extends Comparable> Map<K, V> sortMapByValues(Map<K, V> aMap) {
        HashMap<K, V> finalOut = new LinkedHashMap<>();
        aMap.entrySet().stream().sorted((p1, p2) -> p2.getValue().compareTo(p1.getValue()))
                .collect(Collectors.toList()).forEach(ele -> finalOut.put(ele.getKey(), ele.getValue()));
        return finalOut;
    }

    /**
     * 获取登录用户
     */
    public static UserDto getLoginUser() {
        UserDto userDto = (UserDto) StpUtil.getTokenSession().get(SysConstants.LOGIN_USER);
        if (ObjectUtil.isNull(userDto)) {
            throw NotLoginException.newInstance(null, null);
        }
        return userDto;
    }

    /**
     * 清除菜单缓存
     */
    public void clearMenuCache() {
        String key = Pattern.matches("\\*$", SysConstants.MENU) ? SysConstants.MENU : SysConstants.MENU + "*";
        Set<String> keys = redisTemplate.keys(key);
        if (CollUtil.isNotEmpty(keys)) {
            redisTemplate.delete(keys);
        }
    }

}
